package com.roadrunner;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import android.support.v4.app.LoaderManager;
import android.os.Bundle;
import android.os.StrictMode;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.app.ListFragment;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.Intent;
import android.support.v4.content.Loader;
import android.content.SharedPreferences;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;

public class JobsList extends FragmentActivity
	implements LoaderManager.LoaderCallbacks<String>, listOrderFragment.OnHeadlineSelectedListener, ActivityCommunicator {
	
	public FragmentCommunicator fragmentCommunicator;
	JsonController 					mJC = null;
	private static ArrayList<Job>	m_JobsList = null;
	listOrderFragment firstFragment = null;
	private void MainActivityMainActivity() {
		// TODO Auto-generated method stub

	}
	private String sServer = null;
	public static String curentUserName = "";
	
	private String sActivityName = "JobsList";
	private int JobType = 0;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_jobs_list);
						
		// get the server address
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);	
		try {
			sServer = prefs.getString("CurrentServer", "");
			curentUserName = prefs.getString("CurrentUserName", "");
		} catch (Exception e) {
		    e.printStackTrace();
		}
		
		Bundle extras = getIntent().getExtras(); 
		if (extras != null)
			JobType = extras.getInt("JOB");
		
		Bundle b = new Bundle();
		
		switch(JobType)
		{
		case MainActivity.JOB_GET_ALL:
			{
				String url = sServer + "viewJobs";
				setTitle("All jobs");
				b.putInt("requestFunction", MainActivity.JOB_GET_ALL);
				b.putString("URL_CALL", url);
			}
			break;
			
		case MainActivity.JOB_GET_MY:
			{
				
				String url = sServer + "viewMyJobs?USER=";
				setTitle("My jobs");
				if (extras != null)
					url = url + extras.getString("USER");
				
				b.putInt("requestFunction", MainActivity.JOB_GET_MY);
				b.putString("URL_CALL", url);
				
			}
			break;
		}
		     
		MyHttp loader =  (MyHttp) getSupportLoaderManager().initLoader(0, b, this);
		loader.forceLoad(); 
		
		if (findViewById(R.id.fragment_container) != null) 
		{	
            // Create an instance of ExampleFragment
            firstFragment = new listOrderFragment();
            getIntent().putExtra("FROM", sActivityName);
            firstFragment.setArguments(getIntent().getExtras());

            // Add the fragment to the 'fragment_container' FrameLayout
            getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, firstFragment).commit();
        }
	}
	
	/* (non-Javadoc)
	 * @see android.support.v4.app.FragmentActivity#onStart()
	 */
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
	}
	
	public void updateUI(String text)
	{
		if(text.length() == 0)
			return;
		
		try {
		    //String serverResponse = prefs.getString(sPrefTag, "");		    
		    mJC = new JsonController();
		    m_JobsList =  mJC.parseOrders(text);
		} catch (Exception e) {
		    e.printStackTrace();
		}
		
		fragmentCommunicator.passDataToFragment("Hi from FragmentActivity");
		
		//Fragment f = getSupportLoaderManager.findFragmentById(R.id.fragment_container);
       // f.setData(result);
	}
	
	public void onArticleSelected(int position)
	{
        // The user selected an order from the orders list

        // Capture the article fragment from the activity layout
		OrderFragment orderFragment = (OrderFragment)getSupportFragmentManager().findFragmentById(R.id.orderDetails);

        if (orderFragment != null) {
            // If article frag is available, we're in two-pane layout... and we have to update the fragment
        	orderFragment.updateArticleView(position);
        } 
        else 
        {
            // If the frag is not available, we're in the one-pane layout and must swap frags...
        	OrderFragment newFragment = new OrderFragment();
            Bundle args = new Bundle();
            args.putInt(OrderFragment.ARG_POSITION, position);
            args.putString("FROM", sActivityName);
            newFragment.setArguments(args);
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

            // Replace whatever is in the fragment_container view with this fragment,
            // and add the transaction to the back stack so the user can navigate back
            transaction.replace(R.id.fragment_container, newFragment);
            transaction.addToBackStack(null);

            // Commit the transaction
            transaction.commit();
        }
    }
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{		
		switch(item.getItemId())
		{
		case R.id.home:
			finish();
			//startActivity(new Intent(this, MainActivity.class));
			break;
			
		case R.id.my_jobs:
			{
				Intent newIntent = new Intent(this, JobsList.class);
				Bundle args = new Bundle();
	            args.putInt("JOB", MainActivity.JOB_GET_MY);
	            args.putString("USER", curentUserName);
	            newIntent.putExtras(args);
				startActivity(newIntent);
			}
			break;
		
		case R.id.jobs_list:
			break;
		
		case R.id.action_settings:
			break;
			
		case R.id.exit_app:
			System.exit(0);
			break;
			
		default:
			break;
			
		}
		
		return super.onOptionsItemSelected(item);
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		//System.exit(0);
	}
	
	public static ArrayList<Job> getJobList()
	{
		return m_JobsList;
	}

	@Override
	public void onLoadFinished(Loader<String> arg0, String arg1) {
		// TODO Auto-generated method stub
		
		updateUI(arg1);
	}

	@Override
	public void onLoaderReset(Loader<String> arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public Loader<String> onCreateLoader(int arg0, Bundle arg1) {
		// TODO Auto-generated method stub
		MyHttp http = new MyHttp(this, arg1);	
			return http;
	}

	@Override
	public void passDataToActivity(String someValue) {
		// TODO Auto-generated method stub
		// save the state, make an update in the job
	//	if(someValue.compareTo("SAVE") == 0)
	//	{
		String[] splitted = someValue.split(",");
		
			String url = sServer + splitted[0];
			Bundle b = new Bundle();
			b.putInt("requestFunction", MainActivity.JOB_SAVE_STATE);
			b.putString(splitted[1],splitted[2]);
			b.putString(splitted[3],splitted[4]);
			if(splitted[4].equals("RESERVED"))
				b.putString("transporter_name", curentUserName);
			
			b.putString("URL_CALL", url);
			
			MyHttp loader =  (MyHttp) getSupportLoaderManager().restartLoader(0, b, this);
			loader.forceLoad(); 	
	//	}
	}

}
